﻿using System;
using Fee.Orders.AuthProjectWorkflow;
using Fee.Orders.FormalWorkflow;
using Fee.Orders.PreWorkflow;
using Fee.Stores;
using Identity;
using JwtWebApi.Data;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace JwtWebApi.Controllers
{
    [Route("manage/[controller]")]
    [ApiController]
    [EnableCors]
    public class EventController : Controller
    {
        private readonly AuthProjectManager<ApplicationDbContext> _authProjectManager;
        private readonly IConstructionTaskStore<ApplicationDbContext> _constructionTask;
        private readonly ApplicationDbContext _context;
        private readonly FormalOrderManager<ApplicationDbContext> _formalOrderManager;
        private readonly ILogger<EventController> _logger;
        private readonly PreDelgateOrderManager<ApplicationDbContext> _preDelegateManager;
        private readonly IStationStore<ApplicationDbContext> _stationStore;

        public EventController(IStationStore<ApplicationDbContext> stationStore,
            ApplicationDbContext context
            , FormalOrderManager<ApplicationDbContext> formalOrderManager,
            PreDelgateOrderManager<ApplicationDbContext> preDelegateManager,
            AuthProjectManager<ApplicationDbContext> authProjectManager,
            IConstructionTaskStore<ApplicationDbContext> constructionTask,
            ILogger<EventController> logger
        )
        {
            _stationStore = stationStore;
            _context = context;
            _formalOrderManager = formalOrderManager;
            _preDelegateManager = preDelegateManager;
            _authProjectManager = authProjectManager;
            _constructionTask = constructionTask;
            _logger = logger;
        }

        [HttpGet("s1")]
        public IActionResult S1([FromQuery] StationSetting setting)
        {
            var station = _stationStore.GetByCode(setting.Code);
            station.ThirdStationStatus = "S1已完成";
            //station.ThirdPartyWorkOrderId = setting.WorkfowOrderId;

            _context.SaveChanges();
            var user = _context.SystemUser();
            var trans = _context.Database.BeginTransaction();
            try
            {
                var result = _preDelegateManager.CreateOrder(station.Id, user.UserName, DateTimeOffset.Now,
                    setting.WorkflowOrderId);
                if (result.Successed)
                {
                    result.Order.ThirdPartyWorkflowId = setting.WorkflowOrderId;
                    if (result.Order.Id <= 0)
                        _context.Add(result.Order);
                    _context.SaveChanges();
                    _preDelegateManager.Start(result.Order);
                }

                trans.Commit();
                return Json(new
                {
                    successed = result.Successed,
                    message = result.Message
                });
            }
            catch (Exception ex)
            {
                trans.Rollback();
                _logger.LogError(ex, "创建预委托单失败.");
                return Json(new
                {
                    successed = false,
                    message = "创建预委托单失败"
                });
            }
        }

        [HttpGet("s3")]
        public IActionResult S3([FromQuery] StationSetting setting)
        {
            var station = _stationStore.GetByCode(setting.Code);
            station.ThirdStationStatus = "S3已完成";
            _context.SaveChanges();

            try
            {
                var task = _constructionTask.GetByStation(station.Id);
                var user = _context.SystemUser();
                var result = _formalOrderManager.CreateOrTryToStart(task, user);
                // _formalOrderManager.Start(result);
                return Json(new
                {
                    successed = true,
                    message = "成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建正式委托单失败");
                return Json(new
                {
                    successed = false,
                    message = "创建正式委托单失败"
                });
            }
        }

        [HttpGet("inspected")]
        public IActionResult Inspected([FromQuery] StationChange setting)
        {
            var station = _stationStore.GetByCode(setting.Code);
            station.ThirdStationStatus = setting.Status;
            _context.SaveChanges();
            return Json(new
            {
                successed = true,
                message = "成功"
            });
        }

        public class StationSetting
        {
            public string Code { get; set; }

            public string WorkflowOrderId { get; set; }
        }

        public class StationChange
        {
            public string Code { get; set; }
            public string Status { get; set; }
        }
    }
}